#include "videoplayermodel.h"
#include <QFileInfo>
#include <QDebug>

/**
 * @brief 构造函数
 * @param parent 父对象
 */
VideoPlayerModel::VideoPlayerModel(QObject *parent)
    : QObject(parent)
    , m_player(nullptr)
    , m_playlist(nullptr)
    , m_playState(Stopped)
    , m_playMode(Sequential)
{
    initPlayer();
}

/**
 * @brief 析构函数
 */
VideoPlayerModel::~VideoPlayerModel()
{
    if (m_player) {
        m_player->stop();
        delete m_player;
        m_player = nullptr;
    }

    if (m_playlist) {
        delete m_playlist;
        m_playlist = nullptr;
    }
}

/**
 * @brief 初始化播放器
 */
void VideoPlayerModel::initPlayer()
{
    // 创建播放列表
    m_playlist = new QMediaPlaylist(this);
    m_playlist->setPlaybackMode(QMediaPlaylist::Sequential);

    // 创建播放器
    m_player = new QMediaPlayer(this);
    m_player->setPlaylist(m_playlist);
    m_player->setVolume(50); // 默认音量50%

    // 连接播放器信号
    connect(m_player, &QMediaPlayer::stateChanged,
            this, &VideoPlayerModel::onPlayerStateChanged);
    connect(m_player, &QMediaPlayer::positionChanged,
            this, &VideoPlayerModel::positionChanged);
    connect(m_player, &QMediaPlayer::durationChanged,
            this, &VideoPlayerModel::durationChanged);
    connect(m_player, &QMediaPlayer::volumeChanged,
            this, &VideoPlayerModel::volumeChanged);
    connect(m_player, static_cast<void(QMediaPlayer::*)(QMediaPlayer::Error)>(&QMediaPlayer::error),
            this, &VideoPlayerModel::onPlayerError);

    // 连接播放列表信号
    connect(m_playlist, &QMediaPlaylist::currentIndexChanged,
            this, &VideoPlayerModel::onPlaylistCurrentIndexChanged);
}

// ========== 播放控制接口实现 ==========

/**
 * @brief 开始播放
 */
void VideoPlayerModel::play()
{
    if (m_playlist->mediaCount() == 0) {
        qWarning() << "Playlist is empty, cannot play";
        emit errorOccurred(tr("播放列表为空"));
        return;
    }

    m_player->play();
}

/**
 * @brief 暂停播放
 */
void VideoPlayerModel::pause()
{
    m_player->pause();
}

/**
 * @brief 停止播放
 */
void VideoPlayerModel::stop()
{
    m_player->stop();
}

/**
 * @brief 跳转到指定位置
 * @param position 目标位置（毫秒）
 */
void VideoPlayerModel::seek(qint64 position)
{
    if (position >= 0 && position <= m_player->duration()) {
        m_player->setPosition(position);
    }
}

/**
 * @brief 播放上一个视频
 */
void VideoPlayerModel::previous()
{
    m_playlist->previous();
}

/**
 * @brief 播放下一个视频
 */
void VideoPlayerModel::next()
{
    m_playlist->next();
}

/**
 * @brief 设置音量
 * @param volume 音量值（0-100）
 */
void VideoPlayerModel::setVolume(int volume)
{
    if (volume >= 0 && volume <= 100) {
        m_player->setVolume(volume);
    }
}

/**
 * @brief 设置播放速度
 * @param rate 播放速度（0.5x, 1.0x, 1.5x, 2.0x等）
 */
void VideoPlayerModel::setPlaybackRate(qreal rate)
{
    if (rate > 0.0 && rate <= 2.0) {
        m_player->setPlaybackRate(rate);
    }
}

// ========== 播放列表管理接口实现 ==========

/**
 * @brief 添加视频到播放列表
 * @param filePath 视频文件路径
 * @return 是否添加成功
 */
bool VideoPlayerModel::addMedia(const QString &filePath)
{
    QFileInfo fileInfo(filePath);
    
    // 检查文件是否存在
    if (!fileInfo.exists()) {
        qWarning() << "File does not exist:" << filePath;
        emit errorOccurred(tr("文件不存在: %1").arg(filePath));
        return false;
    }

    // 检查是否为支持的视频格式
    QStringList supportedFormats = {"mp4", "avi", "mkv", "flv", "mov", "wmv", "3gp", "webm"};
    QString suffix = fileInfo.suffix().toLower();
    
    if (!supportedFormats.contains(suffix)) {
        qWarning() << "Unsupported format:" << suffix;
        emit errorOccurred(tr("不支持的视频格式: %1").arg(suffix));
        return false;
    }

    // 添加到播放列表
    bool success = m_playlist->addMedia(QUrl::fromLocalFile(filePath));
    
    if (success) {
        qDebug() << "Media added successfully:" << filePath;
        emit playlistChanged();
    } else {
        qWarning() << "Failed to add media:" << filePath;
        emit errorOccurred(tr("添加视频失败: %1").arg(filePath));
    }

    return success;
}

/**
 * @brief 批量添加视频到播放列表
 * @param filePaths 视频文件路径列表
 * @return 成功添加的数量
 */
int VideoPlayerModel::addMediaList(const QStringList &filePaths)
{
    int successCount = 0;

    for (const QString &filePath : filePaths) {
        if (addMedia(filePath)) {
            successCount++;
        }
    }

    qDebug() << "Added" << successCount << "of" << filePaths.size() << "media files";
    return successCount;
}

/**
 * @brief 移除指定索引的视频
 * @param index 视频索引
 * @return 是否移除成功
 */
bool VideoPlayerModel::removeMedia(int index)
{
    if (index < 0 || index >= m_playlist->mediaCount()) {
        qWarning() << "Invalid index:" << index;
        return false;
    }

    bool success = m_playlist->removeMedia(index);
    
    if (success) {
        qDebug() << "Media removed at index:" << index;
        emit playlistChanged();
    }

    return success;
}

/**
 * @brief 清空播放列表
 */
void VideoPlayerModel::clearPlaylist()
{
    m_player->stop();
    m_playlist->clear();
    qDebug() << "Playlist cleared";
    emit playlistChanged();
}

/**
 * @brief 设置当前播放的视频索引
 * @param index 视频索引
 */
void VideoPlayerModel::setCurrentIndex(int index)
{
    if (index >= 0 && index < m_playlist->mediaCount()) {
        m_playlist->setCurrentIndex(index);
    }
}

/**
 * @brief 设置播放模式
 * @param mode 播放模式
 */
void VideoPlayerModel::setPlayMode(PlayMode mode)
{
    if (m_playMode != mode) {
        m_playMode = mode;
        updatePlaylistMode();
        emit playModeChanged(mode);
        qDebug() << "Play mode changed to:" << mode;
    }
}

/**
 * @brief 更新播放列表模式
 */
void VideoPlayerModel::updatePlaylistMode()
{
    switch (m_playMode) {
    case Sequential:
        m_playlist->setPlaybackMode(QMediaPlaylist::Sequential);
        break;
    case Loop:
        m_playlist->setPlaybackMode(QMediaPlaylist::Loop);
        break;
    case CurrentLoop:
        m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        break;
    case Random:
        m_playlist->setPlaybackMode(QMediaPlaylist::Random);
        break;
    }
}

// ========== 状态查询接口实现 ==========

/**
 * @brief 获取当前播放状态
 * @return 播放状态
 */
VideoPlayerModel::PlayState VideoPlayerModel::playState() const
{
    return m_playState;
}

/**
 * @brief 获取当前播放位置
 * @return 播放位置（毫秒）
 */
qint64 VideoPlayerModel::position() const
{
    return m_player->position();
}

/**
 * @brief 获取当前视频总时长
 * @return 总时长（毫秒）
 */
qint64 VideoPlayerModel::duration() const
{
    return m_player->duration();
}

/**
 * @brief 获取当前音量
 * @return 音量值（0-100）
 */
int VideoPlayerModel::volume() const
{
    return m_player->volume();
}

/**
 * @brief 获取当前播放速度
 * @return 播放速度
 */
qreal VideoPlayerModel::playbackRate() const
{
    return m_player->playbackRate();
}

/**
 * @brief 获取当前视频索引
 * @return 视频索引
 */
int VideoPlayerModel::currentIndex() const
{
    return m_playlist->currentIndex();
}

/**
 * @brief 获取播放列表总数
 * @return 视频数量
 */
int VideoPlayerModel::mediaCount() const
{
    return m_playlist->mediaCount();
}

/**
 * @brief 获取当前播放模式
 * @return 播放模式
 */
VideoPlayerModel::PlayMode VideoPlayerModel::playMode() const
{
    return m_playMode;
}

/**
 * @brief 获取指定索引的媒体URL
 * @param index 视频索引
 * @return 媒体URL
 */
QUrl VideoPlayerModel::mediaUrl(int index) const
{
    if (index >= 0 && index < m_playlist->mediaCount()) {
        return m_playlist->media(index).canonicalUrl();
    }
    return QUrl();
}

/**
 * @brief 获取媒体播放器对象（用于View层连接视频输出）
 * @return QMediaPlayer指针
 */
QMediaPlayer* VideoPlayerModel::mediaPlayer() const
{
    return m_player;
}

// ========== 内部槽函数实现 ==========

/**
 * @brief 处理播放器状态变化
 * @param state QMediaPlayer状态
 */
void VideoPlayerModel::onPlayerStateChanged(QMediaPlayer::State state)
{
    PlayState newState = Stopped;

    switch (state) {
    case QMediaPlayer::StoppedState:
        newState = Stopped;
        break;
    case QMediaPlayer::PlayingState:
        newState = Playing;
        break;
    case QMediaPlayer::PausedState:
        newState = Paused;
        break;
    }

    if (m_playState != newState) {
        m_playState = newState;
        emit playStateChanged(newState);
        qDebug() << "Play state changed to:" << newState;
    }
}

/**
 * @brief 处理播放列表当前项变化
 * @param position 新的位置
 */
void VideoPlayerModel::onPlaylistCurrentIndexChanged(int position)
{
    if (position >= 0) {
        qDebug() << "Current media changed to index:" << position;
        emit currentMediaChanged(position);
    }
}

/**
 * @brief 处理播放器错误
 * @param error 错误类型
 */
void VideoPlayerModel::onPlayerError(QMediaPlayer::Error error)
{
    QString errorString;

    switch (error) {
    case QMediaPlayer::NoError:
        return;
    case QMediaPlayer::ResourceError:
        errorString = tr("资源错误：无法加载媒体文件");
        break;
    case QMediaPlayer::FormatError:
        errorString = tr("格式错误：不支持的媒体格式");
        break;
    case QMediaPlayer::NetworkError:
        errorString = tr("网络错误：无法访问网络资源");
        break;
    case QMediaPlayer::AccessDeniedError:
        errorString = tr("访问被拒绝：没有权限访问该文件");
        break;
    case QMediaPlayer::ServiceMissingError:
        errorString = tr("服务缺失：媒体服务不可用");
        break;
    default:
        errorString = tr("未知错误");
        break;
    }

    qWarning() << "Player error:" << errorString;
    emit errorOccurred(errorString);
}

